package bancosys.tec.security.impl.services.executar;

import javax.security.auth.Subject;

import jmine.tec.di.annotation.Injected;
import jmine.tec.security.impl.SecurityMessages;
import jmine.tec.services.annotations.Execution;
import jmine.tec.services.annotations.Input;
import jmine.tec.services.annotations.ServiceImplementor;
import jmine.tec.services.api.ActionsEnum;
import jmine.tec.services.api.ServiceValidationExecutionException;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import bancosys.tec.security.SecurityException;

/**
 * Serviço para executar login de usuário.
 * 
 * @author rodrigok
 */
@ServiceImplementor(action = ActionsEnum.EXECUTAR)
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class UserService {

    public static final String USERNAME = "Usuário";

    public static final String PASSWORD = "Senha";

    // Obrigatórios
    private String user;

    private String password;

    // Injected
    private bancosys.tec.security.SecurityManager<?> securityManager;

    /**
     * Executa login do usuário.
     * 
     * @throws SecurityException SecurityException
     */
    @Execution
    public void execute() throws SecurityException {
        Subject subject = this.securityManager.login(this.user, this.password, null);
        if (subject == null) {
            throw new ServiceValidationExecutionException(SecurityMessages.USER_PASSWORD_NOT_FOUND.create());
        }
        this.securityManager.getSecurityService().setCurrentThreadSubject(subject);
    }

    /**
     * @param user Nome do usuário.
     */
    @Input(fieldName = USERNAME)
    public void setUser(String user) {
        this.user = user;
    }

    /**
     * @param password Senha do usuário.
     */
    @Input(fieldName = PASSWORD)
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @param securityManager {@link SecurityManager}
     */
    @Injected
    public void setSecurityManager(bancosys.tec.security.SecurityManager securityManager) {
        this.securityManager = securityManager;
    }

}
